package com.ltmonitor.web.controller;

import com.alibaba.druid.stat.TableStat.Mode;
import com.ltmonitor.adas.entity.AdasAlarm;
import com.ltmonitor.entity.Alarm;
import com.ltmonitor.entity.MediaItem;
import com.ltmonitor.service.IAdasAlarmService;
import com.ltmonitor.service.IMediaItemService;
import com.ltmonitor.web.util.FileToZip;
import com.ltmonitor.web.util.JsonMessage;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 终端信息
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/adasAlarm")
public class AdasAlarmAction extends PaginateAction {
	

	@Autowired
	private IAdasAlarmService adasAlarmService;

	@RequestMapping("/viewAdasAlarmProcessedInfo.action")
	public String viewAdasAlarmProcessedInfo(Model model) {
		model.addAttribute("message", "success");
		log.error("测试日志输出，请求查看报警处理记录查询");
		return "adasAlarm/adasAlarmProcessedInfo";
	}
	
	
	
	/**
	 * 获取zip文件 
	 * 1.获取传递的参数 
	 * 2.获取相关路径 
	 * 3.通过数据库查询所有文件信息 
	 * 4.打包 
	 * 5.如果打包成功，下发成功消息并传递打包文件名
	 * 			如果打包失败，下发失败消息
	 * @param request
	 * @return
	 */
	@RequestMapping("/getZip.action")
	public@ResponseBody JsonMessage getZip(@RequestBody String jsonStr, HttpServletRequest request) {
		List list = new ArrayList();
		try {
			Map<String, Object> map = JSONObject.fromObject(jsonStr);
			if (map != null) {
				String projPath = request.getSession().getServletContext().getRealPath("");// 获取项目绝对路径
				String zipPath = projPath + "/zip";// 获取压缩文件存放路径
				String filesPath = projPath + "/adasAttachment/";// 获取附件存放目录
				String fileName = map.get("plateNo").toString()+"-"+map.get("alarmSourceName").toString()
												+"-"+map.get("alarmTypeName").toString()+"-"+map.get("alarmCount").toString()
												+"-"+(int)( Math.random()*1000)+"-"+map.get("alarmTime").toString();

				// 添加测试文件
				List<String> fileNameList = new ArrayList<String>();
				List<File> fileList = new ArrayList<File>();
//				fileList.add(new File(filesPath + "/aaa.txt"));
//				fileList.add(new File(filesPath + "/bbb.txt"));
				
				
				//获取文件名称
//				System.out.println("+++++++++++++++++++++++");
//				System.out.println("+++++++++++++++++++++++");
//				System.out.println("+++++++++++++++++++++++");
				String queryId = "adasAlarm.selectAttachmentsByAlarmNos";
				List result = queryService.query(queryId, map);
				if(result != null && result.size() > 0) {
					for(Object obj :result) {
//						System.out.println(obj.toString());
						Map<String, Object> mapTemp = (Map<String, Object>)obj;
						Object objTemp = mapTemp.get("filePath");
						if(objTemp != null) {
							String fileNameTemp =(String) objTemp;
//							fileNameTemp = filesPath+fileNameTemp;
							if(!fileNameList.contains(fileNameTemp)){
//								System.out.println(fileNameTemp);
								fileNameList.add(fileNameTemp);
							}
							
						}
					}
				}

				//文件名称列表转换为文件列表
				if(fileNameList.size() > 0) {
					for(Object objTemp:fileNameList) {
						String fileNameTemp = objTemp.toString();
//						System.out.println(fileNameTemp);//////////////////////输出文件名称列表
						fileList.add(new File(filesPath +fileNameTemp));
					}
				}
//				System.out.println("+++++++++++++++");
//				System.out.println("+++++++++++++++");
//				System.out.println("zipPath=" + zipPath);
//				System.out.println("filesPath=" + filesPath);


				

				String flg = FileToZip.filesToZip(fileList, zipPath, fileName);
				if(flg.equals("true")) {
					list.add(fileName);
//					list.add(fileList);
					return json(true, list);
				}else {
//					list.add(flg);
					return json(false, flg);
				}
				
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return json(false, e.getMessage());
		}
		
		return json(true, list);
	}
	
	
	
	@RequestMapping("/viewAttachmentList.action")
	public String viewAttachmentList(Model m,
					   @RequestParam(value = "entityId", required = false, defaultValue="0") long id) {
		try {
			if (id > 0) {
				AdasAlarm mi = this.adasAlarmService.load(id);
				m.addAttribute("alarmNo", mi.getAlarmNo());
			}else
			{
				Map entity = new HashMap();
				entity.put("entityId", 0);
				m.addAttribute("entity", entity);
			}
			//m.addObject("message", "保存成功");

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			m.addAttribute("message","发生错误:"+ex.getMessage());
		}
		return "/adasAlarm/attachmentList";
	}

	@RequestMapping("/getImgsZip.action")
	public void getZip(String zipId,HttpServletRequest request,HttpServletResponse response) {
		List list = new ArrayList();
		list.add("getZip.action");
		list.add(zipId);
		try {
			System.out.println("++++++++++++++++++++++");
			System.out.println("++++++++++++++++++++++");
			System.out.println("++++++++++++++++++++++");
		    Map<String, Object> params =  this.getParams();
		    System.out.println(params.get("zipName"));
			System.out.println("request");
//			System.out.println(request.toString());
			System.out.println("respone");
//			System.out.println(response.toString());
			 System.out.println("requestUrl"+request.getRequestURI()); 
	           System.out.println("contextPath"+request.getContextPath());
			String path = request.getSession().getServletContext().getRealPath("");
			System.out.println("path:"+path);
			File file = new File(path+"/test/aaa.txt");
			if(!file.exists()) {
				file.createNewFile();
			}
			
			File directory = new File("");// 参数为空
	         String courseFile = directory.getCanonicalPath();
	         System.out.println("项目路径");
	         
			OutputStream outputStream = response.getOutputStream();
			
			Long filelength = file.length(); // 获取文件长度
	        byte[] filecontent = new byte[filelength.intValue()];
	        FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            outputStream.write(filecontent);
            
          
			
			
			
			System.out.println("++++++++++++++++++++++");
			System.out.println("++++++++++++++++++++++");
			System.out.println("++++++++++++++++++++++");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
	
}
